
const app = getApp()

Page({
  data: {
    messages: [],
    inputMessage: '',
    toView: '',
    isTyping: false,
    loading:true,
    height: 0,  //屏幕高度
    chatHeight:0,//聊天屏幕高度
  },

  onLoad: function () {
    let _this = this;
    wx.setNavigationBarTitle({
      title: 'ChatGPT 小程序'
    })

      //获取屏幕的高度
      wx.getSystemInfo({
        success(res) {
          _this.setData({
            height: wx.getSystemInfoSync().windowHeight,
            chatHeight: wx.getSystemInfoSync().windowHeight-55
          })
        }
      })
  },

  onInput: function (event) {
    this.setData({
      inputMessage: event.detail.value
    })
  },

  onSend: function () {
    const { messages, inputMessage, isTyping } = this.data

    if (inputMessage === '') {
      return
    }
    messages.push({
      role: 'user',
      content: inputMessage
    })

    this.setData({
      messages,
      inputMessage: '',
      toView: `msg-${messages.length - 1}`,
      isTyping: true
    })
    this.requestChat(inputMessage)
  },

  requestChat: function (message) {
    const { messages } = this.data
    messages.push({
      role: 'other',
      content: '',
      wating:true
    })
    this.setData({
      messages,
      toView: `msg-${messages.length - 1}`,
      isTyping: false
    })
    this.toViewBottomFun();
    const data=this.data.messages.filter(item=>item.role=='user')
    const parm=JSON.stringify(data);
    
    wx.cloud.callFunction({
      name: 'chat',
      data:{parm},
      success: res => {
        const role=res.result.message.role.trim();
        const backmsg = res.result.message.content.trim();
        messages[messages.length - 1]={
          role: role,
          content: backmsg
        };
        this.setData({
          messages,
          toView: `msg-${messages.length - 1}`,
          isTyping: false
        })
        this.toViewBottomFun();
      },
      fail: err => {
        console.error(err)
      }
    })
  },
  toViewBottomFun: function() {
    // 设置屏幕自动滚动到最后一条消息处
    console.log('滚动');
    let that = this;
    wx.createSelectorQuery().select('#viewCommunicationBody').boundingClientRect(function(rect) {
      wx.pageScrollTo({
        scrollTop: rect.height,
        duration: 100 // 滑动速度
      })
      that.setData({
        scrollTop: rect.height - that.data.scrollTop
      });
    }).exec();
  }
})